# -*- coding: gb2312 -*-

from pymongo import MongoClient
from WindPy import *

import time
import datetime
import math


def writeIpoDateToMongoDB(endDateStr = time.strftime('%Y-%m-%d'), fillType='F', DBIP='localhost', DBPort=27017, DBName = 'stocks', collectionPreName = 'ipoDate'):

    w.start()

    resStockID = w.wset('sectorconstituent', 'date=' + endDateStr + ';sectorid=a001010100000000;field=wind_code')

    windStockIdList = resStockID.Data[0]

    ipoDateDictList = []

    allStockIdStr = ''

    client = MongoClient(DBIP, DBPort)
    db = client[DBName]
    collectionName = collectionPreName + '_' + endDateStr
    collection_ipo_date = db[collectionName]

    for i in range(0, len(windStockIdList)):
        allStockIdStr = allStockIdStr + str(windStockIdList[i]) + ','

    resIpoDate = w.wss(allStockIdStr, 'ipo_date')

    stockIpoDict = {}
    for i in range(0, len(windStockIdList)) :
        aStockIdStr = str(windStockIdList[i])
        # Char . is not allowed to be used as key, so replace it and save to MongoDB
        aStockIdStr = aStockIdStr.replace('.', '_')
        stockIpoDict[aStockIdStr] = resIpoDate.Data[0][i].strftime('%Y-%m-%d')
    ipoDateDictList.append(stockIpoDict)
    collection_ipo_date.insert(ipoDateDictList)

    return (windStockIdList)

def writeTradeStatusToMongoDB(startDateStr, endDateStr = time.strftime('%Y-%m-%d'), periodStr = 'M', fillType='F', DBIP='localhost', DBPort=27017, DBName = 'stocks', collectionPreName = 'tradeStatus'):

    periodTransDateList = []
    w.start()

    windDateList = w.tdays(startDateStr, endDateStr, 'Period=' + periodStr).Data[0]
    for transDateObj in windDateList:
        periodTransDateList.append(transDateObj.strftime('%Y%m%d'))

    stockIdList = w.wset('sectorconstituent', 'date=' + endDateStr + ';sectorid=a001010100000000;field=wind_code').Data[0]

    combinedStockIdStr = ''
    for stockIdStr in stockIdList :
        combinedStockIdStr = combinedStockIdStr + stockIdStr + ', '

    dateTradeStatusList = []

    #dateTradeStatusList is the stock trade status with respect to the end day of different periods, the first cell in the
    # list is the stock id list, others are the status string.
    # date string is in periodTransDateList, its length is the same as that of dateTradeStatusList (deduct 1 for the first
    # cell of the first stock id list.

    for periodTransDateStr in periodTransDateList:
        windTradeStatusRes = w.wss(combinedStockIdStr, 'trade_status', 'tradeDate=' + periodTransDateStr)
        windTradeStatusList = windTradeStatusRes.Data[0]
        dateTradeStatusList.append(windTradeStatusList)

    client = MongoClient(DBIP, DBPort)
    db = client[DBName]
    collectionName = collectionPreName + '_' + startDateStr + '-' + endDateStr
    collection_ipo_date = db[collectionName]

    tradeStatusListForDB = []
    for i in range(0, len(stockIdList) ):
        tradeStatusDict = {}
        for j in range(0, len(windDateList)):
            tradeStatusDict['StockID'] = stockIdList[i]
            tradeStatusDict[periodTransDateList[j]] = dateTradeStatusList[j][i]
        tradeStatusListForDB.append(tradeStatusDict)
    collection_ipo_date.insert(tradeStatusListForDB)







#writeIpoDateToMongoDB()

w.start()
result = w.wsd('000001.SZ,000012.SZ,000008.SZ', 'mfd_sellamt_d', '2017-05-04', '2017-05-18', 'traderType=1;Fill=Previous;PriceAdj=B')
print (result)
#writeTradeStatusToMongoDB(startDateStr='2013-01-01')
    #for ipoDate in res.Data[0] :
    #    aIpoDateDict = {}
    #    print (ipoDate.strftime('%Y%m%d'))
